// pages/future/future.js
const APIKEY = "071597b90ac24b8f8808f5400e8b8309"; // KEY

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    legend: {
      data: ['A', 'C'],
      top: 50,
      left: 'center',
      backgroundColor: 'red',
      z: 100,
      show: false
    },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      //  show: false
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      // show: false
    },
    series: [{
      name: 'A',
      type: 'line',
      smooth: true,
      data: [18, 36, 65, 30, 78, 40, 33]
    }, {
      name: 'C',
      type: 'line',
      smooth: true,
      data: [10, 30, 31, 50, 40, 20, 10]
    }]
  };

  chart.setOption(option);
  return chart;
}
Page({
  onShareAppMessage: function (res) {
    return {
      path: '/pages/future/future',
      success: function () {},
      fail: function () {}
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    // ec: {
    //   onInit: initChart
    // }
    location: '',
    daily: [],
    coolTrendDays: 0,
    warmTrendDays: 0,
    rainTrendDays: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLocation()
  },

  //点击上面时，选择定位
  selectLocation() {
    var that = this
    wx.chooseLocation({
      success(res) {
        that.setData({
          location: res.longitude + "," + res.latitude
        })
        that.getWeather()
        that.getCityByLoaction()
      },
      fail() {
        wx.getLocation({
          type: 'gcj02',
          fail() {
            wx.showModal({
              title: '获取地图位置失败',
              content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
              success(mRes) {
                if (mRes.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userLocation"] === true) {
                        that.selectLocation()
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    },
                    fail(err) {
                      console.log(err)
                      wx.showToast({
                        title: '唤起设置页失败，请手动打开',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  })
                }
              }
            })
          }
        })
      }
    })
  },

  /**
   * 在页面加载时，获取当前定位
   */
  getLocation() {
    var that = this
    wx.getLocation({
      // 有多种类型 wgs84、gcj02 
      type: 'gcj02',
      success(res) {
        that.setData({
          // 存储精度跟维度
          location: res.longitude + "," + res.latitude
        })
        that.getWeather()
        that.getCityByLoaction()
      },
      fail(err) {
        wx.showModal({
          title: '获取定位信息失败',
          content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
          success(mRes) {
            if (mRes.confirm) {
              wx.openSetting({
                success: function (data) {
                  if (data.authSetting["scope.userLocation"] === true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    that.getLocation()
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                    that.setData({
                      location: "116.41,39.92"
                    })
                    that.getWeather()
                    that.getCityByLoaction()
                  }
                },
                fail(err) {
                  console.log(err)
                  wx.showToast({
                    title: '唤起设置页失败，请手动打开',
                    icon: 'none',
                    duration: 1000
                  })
                  that.setData({
                    location: "116.41,39.92"
                  })
                  that.getWeather()
                  that.getCityByLoaction()
                }
              })
            } else if (mRes.cancel) {
              that.setData({
                location: "116.41,39.92"
              })
              that.getWeather()
              that.getCityByLoaction()
            }
          }
        })
      }
    })
  },


  /**
   * 根据坐标获取城市信息
   */
  getCityByLoaction() {
    var that = this
    wx.request({
      // 通过坐标向接口发送请求获取信息
      url: 'https://geoapi.qweather.com/v2/city/lookup?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        if (res.code == "200") {
          var data = res.location[0]
          that.setData({
            City: data.adm2,
            County: data.name
          })
        } else {
          wx.showToast({
            title: '获取城市信息失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 获取天气
   */
  getWeather() {
    var that = this
    wx.showLoading({
      title: '加载中',
    })
    // 获取 7 日预报天气
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/7d?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        //console.log(res)
        res.daily.forEach(function (item) {
          item.date = that.formatTime(new Date(item.fxDate)).daily
          item.dateToString = that.formatTime(new Date(item.fxDate)).dailyToString
        })
        that.setData({
          daily: res.daily
        })
        that.calculateTrends(res.daily);
        wx.hideLoading()
      }
    })
  },

  // 计算趋势
  calculateTrends(weatherData) {
    let coolTrendDays = 0;
    let warmTrendDays = 0;
    let rainTrendDays = 0;

    for (let i = 1; i < weatherData.length; i++) {
      const prevDay = weatherData[i - 1];
      const currDay = weatherData[i];

      // 判断降温趋势   前一天的最大气温和最低气温进行判断
      if (parseFloat(currDay.tempMax) < parseFloat(prevDay.tempMax) &&
        parseFloat(currDay.tempMin) < parseFloat(prevDay.tempMin)) {
        coolTrendDays++;
      }

      // 判断升温趋势 前一天的最大气温和最低气温进行判断
      if (parseFloat(currDay.tempMax) > parseFloat(prevDay.tempMax) &&
        parseFloat(currDay.tempMin) > parseFloat(prevDay.tempMin)) {
        warmTrendDays++;
      }

      // 判断降水趋势  preip > 0 就代表有降雨
      if (parseFloat(currDay.precip) > 0) {
        rainTrendDays++;
      }
    }

    this.setData({
      coolTrendDays,
      warmTrendDays,
      rainTrendDays
    });
  },
  // 格式时间
  formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    const weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
    const isToday = date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)
    return {
      hourly: [hour, minute].map(this.formatNumber).join(":"),
      daily: [month, day].map(this.formatNumber).join("-"),
      dailyToString: isToday ? "今天" : weekArray[date.getDay()]
    }
  },
  // 补零 避免 单独一个数字情况
  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },

  navigateToDetail(e) {
    const date = e.currentTarget.dataset.date;
    console.log(date);
    const index = e.currentTarget.dataset.index;
    const location = this.data.location; // 获取当前位置信息
    console.log(location);
    // 更新点击状态
    let daily = this.data.daily.map((item, idx) => {
      item.isActive = idx === index;
      return item;
    });
  
    this.setData({
      daily
    });
  
    // 延时恢复点击效果
    setTimeout(() => {
      daily = this.data.daily.map((item, idx) => {
        item.isActive = false; // 恢复所有项目的点击状态
        return item;
      });
  
      this.setData({
        daily
      });
  
      wx.navigateTo({
        url: `/pages/detail/detail?date=${date}&location=${location}`
      });
    }, 300); // 延时300毫秒后恢复
  },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getLocation();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})